<template>
  <div>
    <el-card class="box-card" style="margin:20px">
      <div slot="header" class="clearfix">
        <el-form :inline="true">
          <el-form-item label="用户名" style="margin-bottom:0px;">
            <el-input v-model="searchForm.username" placeholder="输入名称" />
          </el-form-item>
          <el-form-item label="姓名" style="margin-bottom:0px;">
            <el-input v-model="searchName" placeholder="输入名称" />
          </el-form-item>
          <el-form-item style="margin-bottom:0px;">
            <el-button type="primary" icon="el-icon-search" @click="getUserList">查询</el-button>
            <el-button type="primary" icon="el-icon-edit" @click="add">新增</el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-table v-loading="loading" :data="tableData" style="width: 100%">
        <el-table-column
          prop="username"
          label="用户名"
          width="100px"
        />
        <el-table-column
          prop="name"
          label="姓名"
          width="100px"
        />
        <el-table-column
          prop="roleId"
          label="角色"
          :formatter="formatRole"
          width="180px"
        />
        <el-table-column
          prop="systemName"
          label="所属系统"
        />
        <el-table-column
          prop="active"
          label="状态"
          :formatter="formatActive"
          width="120px"
        />
        <el-table-column
          align="center"
          label="操作"
          width="280px"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-edit"
              @click="update(scope.$index, scope.row)"
            >
              修改
            </el-button>
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-edit"
              @click="updatePass(scope.$index, scope.row)"
            >
              修改密码
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="block" style="float:right;margin:20px">
        <el-pagination
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
      <div>
        <el-dialog title="用户信息" :visible.sync="dialogFormVisible">
          <el-form ref="userForm" label-width="100px" size="mini" :model="userForm" :rules="rules">
            <el-form-item label="用户名" prop="username">
              <el-input
                v-model="userForm.username"
              />
            </el-form-item>
            <el-form-item label="姓名" prop="name">
              <el-input
                v-model="userForm.name"
              />
            </el-form-item>
            <el-form-item v-if="role === 1" label="角色" prop="roleId">
              <el-select v-model="userForm.roleId" placeholder="请选择" style="width:100%;">
                <el-option
                  v-for="item in roleOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="所属系统" prop="systemIds">
              <el-select v-model="userForm.systemIds" multiple placeholder="请选择" style="width:100%;">
                <el-option
                  v-for="item in systemOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="状态" prop="active">
              <el-radio-group v-model="userForm.active">
                <el-radio :label="0">不可用</el-radio>
                <el-radio :label="1">可用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="saveOrUpdate">确 定</el-button>
          </div>
        </el-dialog>
        <el-dialog title="修改密码" :visible.sync="dialogPasswordVisible">
          <el-form ref="passwordForm" label-width="100px" size="mini" :model="passwordForm" :rules="passwordRules">
            <el-form-item label="原密码" prop="oldPassword">
              <el-input
                v-model="passwordForm.oldPassword"
                type="password"
              />
            </el-form-item>
            <el-form-item label="新密码" prop="newPassword">
              <el-input
                v-model="passwordForm.newPassword"
                type="password"
              />
            </el-form-item>
            <el-form-item label="确认密码" prop="checkPassword">
              <el-input
                v-model="passwordForm.checkPassword"
                type="password"
              />
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogPasswordVisible = false">取 消</el-button>
            <el-button type="primary" @click="updatePassword">确 定</el-button>
          </div>
        </el-dialog>
      </div>
    </el-card>
  </div>
</template>
<script>
export default {
  data() {
    var validateUsername = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入用户名'))
      } else {
        if (this.userForm.username !== '') {
          const params = new FormData()
          params.append('username', this.userForm.username)
          params.append('updateUserId', this.updateUserId)
          this.$axios.post(this.basePortalUrl + '/user/validateUsername',
            params
          ).then(res => {
            if (res.data.data) {
              // this.$refs.userForm.validateField('username')
              callback()
            } else {
              callback(new Error('用户名已存在，请重新输入'))
            }
          }).catch(() => {
            callback(new Error('请输入用户名'))
            this.$message.error('校验用户名失败')
          })
        }
      }
    }
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (this.passwordForm.checkPassword !== '') {
          this.$refs.passwordForm.validateField('checkPassword')
        }
        callback()
      }
    }
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.passwordForm.newPassword) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      role: this.$store.state.user.roles[0],
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogFormVisible: false,
      userForm: {
        username: '',
        name: '',
        roleId: '',
        systemIds: [],
        active: 0
      },
      rules: {
        username: [
          { validator: validateUsername, trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        roleId: [
          { required: true, message: '请选择角色', trigger: 'change' }
        ],
        systemIds: [
          { required: true, message: '请选择业务系统', trigger: 'change' }
        ]
      },
      updateUserId: 0,
      roleOptions: [
        {
          label: '超级管理员',
          value: 1
        },
        {
          label: '管理员',
          value: 2
        },
        {
          label: '普通用户',
          value: 3
        }
      ],
      systemOptions: [],
      searchName: '',
      dialogPasswordVisible: false,
      passwordForm: {
        oldPassword: '',
        newPassword: '',
        checkPassword: ''
      },
      passwordRules: {
        oldPassword: [
          { required: true, message: '请输入原密码', trigger: 'blur' }
        ],
        newPassword: [
          { validator: validatePass, trigger: 'blur' }
        ],
        checkPassword: [
          { validator: validatePass2, trigger: 'blur' }
        ]
      },
      searchForm: {
        username: ''
      }
    }
  },
  mounted() {
    this.getUserList()
    this.getSystemOptions()
  },
  methods: {
    getUserList() {
      this.loading = true
      var params = {
        'pageSize': this.pageSize,
        'pageNum': this.currentPage,
        'name': this.searchName,
        'username': this.searchForm.username
      }
      this.$axios.get(this.basePortalUrl + '/user/page', {
        params
      }).then(res => {
        this.tableData = res.data.data.records
        this.total = parseInt(res.data.data.total)
        this.loading = false
      }).catch(() => {
        this.loading = false
        this.$message.error('获取用户列表失败')
      })
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
      this.getUserList()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.getUserList()
    },
    add() {
      if (this.$refs['userForm'] !== undefined) {
        this.$refs['userForm'].resetFields()
      }
      this.$set(this.userForm, 'username', '')
      this.$set(this.userForm, 'name', '')
      this.$set(this.userForm, 'active', 0)
      this.$set(this.userForm, 'roleId', '')
      this.$set(this.userForm, 'systemIds', '')
      this.updateUserId = 0
      this.dialogFormVisible = true
    },
    update(index, row) {
      if (this.$refs['userForm'] !== undefined) {
        this.$refs['userForm'].resetFields()
      }
      this.$set(this.userForm, 'username', row.username)
      this.$set(this.userForm, 'name', row.name)
      this.$set(this.userForm, 'active', row.active)
      this.$set(this.userForm, 'roleId', row.roleId)
      this.$set(this.userForm, 'systemIds', row.systemIds)
      this.updateUserId = row.id
      this.dialogFormVisible = true
    },
    saveOrUpdate() {
      this.$refs['userForm'].validate((valid) => {
        if (valid) {
          var params = {
            'username': this.userForm.username,
            'name': this.userForm.name,
            'roleId': this.userForm.roleId,
            'systemIds': this.userForm.systemIds,
            'active': this.userForm.active
          }
          var url = this.basePortalUrl + '/user/create'
          if (this.updateUserId != 0){//eslint-disable-line
            url = this.basePortalUrl + '/user/update'
            this.$set(params, 'id', this.updateUserId)
          }
          this.$axios.post(url,
            params
          ).then(res => {
            this.dialogFormVisible = false
            this.getUserList()
            this.$message.success('操作成功~')
          }).catch(() => {
            this.$message.error('操作失败！')
          })
        } else {
          this.$message.error('请正确输入')
          return false
        }
      })
    },
    remove(index, row) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        this.$axios.delete(this.basePortalUrl + '/user/remove', {
          params: {
            id: row.id
          }
        }).then(res => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getUserList()
        }).catch(() => {
          this.$message({
            type: 'error',
            message: '删除失败'
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    formatRole(row, column, cellValue, index) {
      switch (row.roleId) {
        case 1:
          return '超级管理员'
        case 2:
          return '管理员'
        case 3:
          return '普通用户'
        default:
          return '未知'
      }
    },
    formatActive(row, column, cellValue, index) {
      if (row.active == 0) {//eslint-disable-line
        return '不可用'
      } else {
        return '可用'
      }
    },
    getSystemOptions() {
      this.$axios.get(this.basePortalUrl + '/system/findAll'
      ).then(res => {
        this.systemOptions = res.data.data
      }).catch(() => {
        this.$message.error('获取业务系统失败')
      })
    },
    updatePass(index, row) {
      this.updateUserId = row.id
      this.$set(this.passwordForm, 'oldPassword', '')
      this.$set(this.passwordForm, 'newPassword', '')
      this.$set(this.passwordForm, 'checkPassword', '')
      this.dialogPasswordVisible = true
    },
    updatePassword() {
      this.$refs['passwordForm'].validate((valid) => {
        if (valid) {
          const params = new FormData()
          params.append('oldPassword', this.passwordForm.oldPassword)
          params.append('newPassword', this.passwordForm.newPassword)
          params.append('updateUserId', this.updateUserId)
          this.$axios.post(this.basePortalUrl + '/user/updatePassword',
            params
          ).then(res => {
            if (res.data.data) {
              this.$message.success('密码修改成功')
              this.dialogPasswordVisible = false
            } else {
              this.$message.error('原密码错误')
            }
          }).catch(() => {
            this.$message.error('密码修改失败')
          })
        } else {
          this.$message.error('请正确输入')
          return false
        }
      })
    }

  }
}
</script>
<style scoped>

</style>
